package com.olympia.myapp.activity;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.xml.sax.InputSource;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.olympia.myapp.R;
import com.olympia.myapp.adapter.PlayerAdapter;
import com.olympia.myapp.base.BaseActivity;
import com.olympia.myapp.custom.Dialog_AddMoney;
import com.olympia.myapp.custom.Dialog_AddMoney.ProcessDialogAddMoney;
import com.olympia.myapp.custom.Dialog_Confirm;
import com.olympia.myapp.custom.Dialog_Confirm.ProcessDialogConfirm;
import com.olympia.myapp.entity.Player;
import com.olympia.myapp.server.HttpConnection;
import com.olympia.myapp.util.Constants;
import com.olympia.myapp.util.Settings;
import com.olympia.myapp.xml.MyXMLParser;

public class PlayerListActivity extends BaseActivity {
	ProgressBar progress = null;
	ListView lstPlayer = null;
	PlayerAdapter adapter = null;
	Dialog_Confirm dgConfirm = null;
	Dialog_AddMoney dgAdd = null;
	Button btnReplay = null;
	Button btnPlay = null;
	TextView txtContentFirst = null;
	TextView txtContentSecond = null;
	TextView txtContentThird = null;
	TextView txtName = null;
	TextView txtMail = null;
	TextView txtCoin = null;
	String pass = "";
	int typeConnect = 0;// 0 lấy danh sách top, 1 nạp xu
	String urlQuestion = "";
	String urlLoginAuto = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player_list);
		intent = getIntent();

		// admdob
		// AdView adView = (AdView) this.findViewById(R.id.adView);
		// adView.bringToFront();
		// AdRequest rq = new AdRequest();
		// rq.setTesting(true);
		// adView.loadAd(rq);

		Constants.myService.playBegin();

		pass = intent.getExtras().getString("pass");

		progress = (ProgressBar) findViewById(R.id.progress);
		btnPlay = (Button) findViewById(R.id.player_list_content_play);
		btnReplay = (Button) findViewById(R.id.player_list_content_replay);

		txtContentFirst = (TextView) findViewById(R.id.layer_list_content_first);
		txtContentSecond = (TextView) findViewById(R.id.layer_list_content_second);
		txtContentThird = (TextView) findViewById(R.id.layer_list_content_third);
		txtName = (TextView) findViewById(R.id.layer_list_namePlayer);
		txtMail = (TextView) findViewById(R.id.layer_list_mailPlayer);
		txtCoin = (TextView) findViewById(R.id.layer_list_coin);

		if (Constants.myAccount != null) {
			addContent();
		}

		lstPlayer = (ListView) findViewById(R.id.player_list_listview);
		adapter = new PlayerAdapter(PlayerListActivity.this);
		lstPlayer.setAdapter(adapter);

		// kiểm tra điểm số
		checkRetect();

		// tiến hành đọc bộ câu hỏi cho lần chơi này
		typeConnect = 1;
		urlQuestion = urlUtil.getAllQuestion(Constants.VERSION,
				Constants.myAccount.mail, pass);
		requestServer(urlQuestion);
	}

	private void addContent() {
		Resources res = getResources();
		String text1 = String.format(res.getString(R.string.play_content1),
				Constants.myAccount.level);
		txtContentFirst.setText(text1);

		String text2 = String.format(res.getString(R.string.play_content2),
				Constants.myAccount.score, Constants.myAccount.order);
		txtContentSecond.setText(text2);

		txtName.setText(Constants.myAccount.name);
		txtMail.setText(Constants.myAccount.mail);

		String tCoin = String.format(res.getString(R.string.play_content3),
				Constants.myAccount.coin);
		txtCoin.setText(tCoin);
	}

	/**
	 * kiem tra xu co con de choi khong
	 */
	private void checkRetect() {
		if (Constants.myAccount.mail.toUpperCase().compareTo(
				getString(R.string.my_mail).toUpperCase()) == 0) {
			Constants.myAccount.retest = "0";
			Constants.myAccount.coin = "10000";
			txtCoin.setText("1000");
		}
		// kiem tra point con hay khong
		if (Integer.parseInt(Constants.myAccount.retest) > 0) {
			btnPlay.setVisibility(View.INVISIBLE);
			btnReplay.setVisibility(View.VISIBLE);
		} else {
			btnPlay.setVisibility(View.VISIBLE);
			btnReplay.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * ẩn hiện progressbar
	 * 
	 * @param isShow
	 */
	private void showhideProgress(boolean isShow) {
		isRequest = isShow;
		progress.setVisibility(isShow ? View.VISIBLE : View.GONE);
	}

	/*
	 * hien thi dialog confirm
	 */
	private void showDialogConfirm(final int type, String title, String content) {
		if (dgConfirm == null) {
			dgConfirm = new Dialog_Confirm(PlayerListActivity.this, title,
					content, true, true, new ProcessDialogConfirm() {
						public void click_Ok() {
							if (type == 1)
								showDialogAddMoney();
						}

						public void click_Cancel() {
						}
					});
		}

		dgConfirm.setContent(content);
		dgConfirm.show();
	}

	private void showDialogAddMoney() {
		dgAdd = new Dialog_AddMoney(PlayerListActivity.this,
				new ProcessDialogAddMoney() {

					public void click_Ok(String cardNum, String cardSeri,
							int typeCard) {
						typeConnect = 100;
						String urlCoin = urlUtil.addCoin(
								Constants.myAccount.mail, cardNum, cardSeri,
								typeCard);
						requestServer(urlCoin);
					}
				});
		dgAdd.show();
	}

	// ====================== Gui yeu cau len server ========================
	public void requestServer(String url) {
		if (!isRequest) {
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message message) {
					switch (message.what) {
					case HttpConnection.DID_START: {
						showhideProgress(true);
						break;
					}
					case HttpConnection.DID_SUCCEED: {
						String result = message.obj.toString();
						showhideProgress(false);
						try {
							processDataResult(result, message.arg1);
						} catch (IOException e) {
							e.printStackTrace();
						}

						break;
					}
					case HttpConnection.DID_ERROR: {
						showhideProgress(false);
						showDialogConfirm(0, getString(R.string.note_title),
								getString(R.string.error_connect));
						break;
					}
					}
				}
			};

			new HttpConnection(handler).get(url, typeConnect);
		}
	}

	private void processDataResult(String str, int index) throws IOException {
		if (str != null && str.length() > 0) {
			switch (index) {
			case 0:// lấy danh sách top
				URL sourceUrl = new URL(
						urlUtil.getTopTen(Constants.myAccount.mail));
				List<Player> content = MyXMLParser
						.parseLayerTopData(new InputSource(sourceUrl
								.openStream()));
				if (content != null && content.size() > 0) {
					for (Player player : content) {
						adapter.add(player);
						adapter.notifyDataSetChanged();
					}
				} else {
					msgUtil.showToast(this, "Dữ liệu không hợp lệ");
				}
				break;
			case 1:// danh sach bo cau hoi
				if (urlQuestion.length() > 0) {
					URL sourceUrlQs = new URL(urlQuestion);
					MyXMLParser.parseQuestionData(new InputSource(sourceUrlQs
							.openStream()));

					// lấy danh sách ng chơi cao điểm nhât
					typeConnect = 0;
					String urlTop = urlUtil.getTopTen(Constants.myAccount.mail);
					requestServer(urlTop);
				}
				break;
			case 2:// xác nhân choi
				if (str.contains("<result>OK</result>")) {
					// chuyen sang form khoi dong
					finish();
					intent = new Intent(PlayerListActivity.this,
							StartActivity.class);
					startActivityForResult(intent, Constants.KEY_PLAER);
					overridePendingTransition(R.anim.fase_in, R.anim.fade_out);
				} else {
					msgUtil.showToast(this, "Không thể tham gia chương trình.");
				}
				break;
			case 3:// gui yeu cau choi lai
				if (str.contains("<result>OK</result>")) {
					// gọi login tự động
					typeConnect = 4;
					String[] account = Settings.getpPlayer(this);
					urlLoginAuto = urlUtil.login(Constants.VERSION, account[0],
							account[1]);
					requestServer(urlLoginAuto);
				} else {
					msgUtil.showToast(this, "Không thể làm mới chương trình.");
				}
				break;
			case 4:// truong hop login tự động{
				URL source = new URL(urlLoginAuto);
				List<String> result = MyXMLParser
						.parseLoginData(new InputSource(source.openStream()));
				if (result != null && result.size() > 0) {
					String[] arr = Settings.getpPlayer(this);
					if (result.get(0).toString().toUpperCase().equals("OK")) {
						Constants.myAccount = new Player(1000, result.get(1),
								arr[0], result.get(2), result.get(3),
								result.get(4), result.get(5), result.get(6));

						addContent();
						checkRetect();

						// tự động xác nhận chơi
						Constants.myAccount.coin = String.valueOf(Integer
								.parseInt(Constants.myAccount.coin)
								- Constants.playPoint);
						// gửi yêu cầu lên server để xác nhận chơi gói câu hỏi
						// này
						typeConnect = 2;
						acceptPlayUrl = urlUtil
								.acceptPlay(Constants.myAccount.mail);
						requestServer(acceptPlayUrl);
					}
				}
				break;
			case 100:// xử lý dữ liệu trả về khi nạp xu
				if (dgAdd != null) {
					if (str.contains("<result>OK</result>"))// nạp thành công
						dgAdd.progress.setVisibility(View.GONE);
					else if (str.contains("<result>ER_02</result>"))
						msgUtil.showToast(this,
								"Lỗi thẻ đã sử dụng hoặc thẻ không hợp lệ");
					else if (str.contains("<result>ER</result>"))
						msgUtil.showToast(this, "Lỗi xin kiểm tra lại");
				}
				break;
			default:
				break;
			}
		}
	}

	// ===============================================================
	/**
	 * 
	 * @param view
	 */
	public void click_Replay(View view) {
		if (Integer.parseInt(Constants.myAccount.coin) >= Constants.playPoint) {
			// gui yêu cầu chơi lại
			typeConnect = 3;
			String urlRetect = urlUtil.playAgain(Constants.VERSION,
					Constants.myAccount.mail);
			requestServer(urlRetect);
		} else {
			String str = String.format(getResources()
					.getString(R.string.alert1), Constants.STRCOINT);
			showDialogConfirm(1, "THÔNG BÁO", str);
		}
	}

	/**
	 * 
	 * @param view
	 */
	String acceptPlayUrl = "";

	public void click_Play(View view) {
		if (Integer.parseInt(Constants.myAccount.coin) >= 0) {
			// gửi yêu cầu lên server để xác nhận chơi gói câu hỏi này
			typeConnect = 2;
			acceptPlayUrl = urlUtil.acceptPlay(Constants.myAccount.mail);
			requestServer(acceptPlayUrl);
		} else {
			String str = String.format(getResources()
					.getString(R.string.alert1), Constants.STRCOINT);
			showDialogConfirm(1, "THÔNG BÁO", str);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.KEY_PLAER) {
			checkRetect();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		Constants.myService.pauseBegin();
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		Constants.myService.pauseBegin();
		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}
}
